package fm.dongman.animefm.view.fragment

import android.annotation.SuppressLint
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import fm.dongman.animefm.R
import kotlinx.android.synthetic.main.fragment_web_player.*

/**
 * 网页播放器
 *
 * Created by shize on 2017/10/31.
 */
class WebVideoFragment : BaseFragment() {
    companion object {
        private val BUNDLE_URL = "fm.dongman.animefm.bundle.url"

        fun newInstance(url: String): WebVideoFragment {
            val fragment = WebVideoFragment()
            val bundle = Bundle()
            bundle.putString(BUNDLE_URL, url)
            fragment.arguments = bundle
            return fragment
        }
    }

    private lateinit var mFragment: View // fragment
    private var mUrl: String = "" // 视频地址

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View {
        mFragment = inflater!!.inflate(R.layout.fragment_web_player, container, false)
        return mFragment
    }

    override fun initData() {
        if (arguments != null)
            mUrl = arguments.getString(BUNDLE_URL)
    }

    override fun bindData() {
        bindWebView()
    }

    /**
     * 绑定 WebView
     */
    @SuppressLint("SetJavaScriptEnabled")
    private fun bindWebView() {
        mVideoWebView.setWebViewClient(VideoWebViewClient())
        mVideoWebView.setWebChromeClient(VideoWebViewChromeClient())
        mVideoWebView.loadUrl(mUrl) // 载入网页地址
        // 设置参数
        val webSettings = mVideoWebView.settings
        webSettings.javaScriptEnabled = true // 启用js
        webSettings.javaScriptCanOpenWindowsAutomatically = true // 启用 js 弹窗
        webSettings.mediaPlaybackRequiresUserGesture = true // 启用媒体播放手势控制
        // 设置适应屏幕
        webSettings.useWideViewPort = true // 将图片调整到适合 webView 的大小
        webSettings.loadWithOverviewMode = true // 缩放至屏幕的大小

    }

//    override fun onConfigurationChanged(newConfig: Configuration?) {
//        super.onConfigurationChanged(newConfig)
//        if (newConfig!!.orientation == Configuration.ORIENTATION_LANDSCAPE) {
//            // 横屏
//            setWebViewLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT)
//        } else {
//            // 竖屏
//            setWebViewLayoutParams(SystemHelper.dipToPx(activity, 200f).toInt())
//        }
//    }

//    /**
//     * 设置 webView 的大小
//     * @param height 高度
//     */
//    private fun setWebViewLayoutParams(height: Int) {
//        val webViewLp = mVideoWebView.layoutParams
//        webViewLp.height = height
//        mVideoWebView.layoutParams = webViewLp
//    }

    override fun onResume() {
        super.onResume()
        mVideoWebView.onResume()
    }

    override fun onPause() {
        super.onPause()
        mVideoWebView.onPause()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        // 移除并销毁 WebView
        mWebVideoRoot.removeView(mVideoWebView)
        mVideoWebView.destroy()
    }

    /**
     * 自定义 WebChromeClient
     * 实现对横竖屏的操作
     */
    private inner class VideoWebViewChromeClient : WebChromeClient() {
        private var mCallBack: CustomViewCallback? = null // 用来存储 callback 用于判断是否隐藏 view

        override fun onShowCustomView(view: View?, callback: CustomViewCallback?) {
            // 将横屏的网页 View 直接交给 FrameLayout 来显示
            fullScreen()
            mVideoWebView.visibility = View.GONE
            mVideoContainer.visibility = View.VISIBLE
            mVideoContainer.addView(view)
            mCallBack = callback
            super.onShowCustomView(view, callback)
        }

        override fun onHideCustomView() {
            fullScreen()
            mCallBack?.onCustomViewHidden()
            mVideoWebView.visibility = View.VISIBLE
            mVideoContainer.removeAllViews()
            mVideoContainer.visibility = View.GONE
            activity.onBackPressed()
        }
    }

    /**
     * WebView 监听完成加载
     */
    private inner class VideoWebViewClient : WebViewClient() {
        override fun onPageFinished(view: WebView?, url: String?) {
            view?.post {
                view.loadUrl("javascript:fullscreen()")
            }
        }
    }

    /**
     * 手动控制横竖全屏
     */
    private fun fullScreen() {
        // setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); 横屏设置
        // setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 竖屏设置
        // setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); 默认设置
        if (resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) {
            activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
        }
    }
}